/**
 * 
 */
package org.t2.game.server.module.rank.service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.gaming.ruler.eventbus.Subscribe;
import org.gaming.ruler.lifecycle.Lifecycle;
import org.gaming.service.service.AbstractService;
import org.gaming.tool.ListMapUtil;
import org.springframework.stereotype.Service;
import org.t2.game.server.module.rank.constant.RankType;
import org.t2.game.server.module.rank.model.Ranker;
import org.t2.game.server.module.recharge.event.RechargeEvent;

/**
 * 
 */
@Service
public class RankerService extends AbstractService<Ranker> implements Lifecycle {

	private ConcurrentMap<RankType, RankerContext> contextMap = new ConcurrentHashMap<>();
	
	@Override
	public void start() throws Exception {
		List<Ranker> allRankers = this.repository().getAll();
		Map<Integer, List<Ranker>> typeRankers = ListMapUtil.fillListMap(allRankers, Ranker::getType);
		
		for(RankType rankType : RankType.values()) {
			RankerContext rankerContext = new RankerContext(rankType);
			List<Ranker> rankers = typeRankers.getOrDefault(rankType.getValue(), Collections.emptyList());
			rankerContext.initRankList(rankers);
			
			contextMap.put(rankType, rankerContext);
		}
	}
	
	public RankerContext getContext(RankType rankType) {
		return contextMap.get(rankType);
	}
	
	@Override
	public void mergeServer(int mergeDbZoneId) {
		//先不考虑合服
	}
	
	@Subscribe
	private void listen(RechargeEvent event) {
		RankerContext rankerContext = contextMap.get(RankType.RECHARGE);
		rankerContext.updateRank(event.getPlayer().getId(), event.getPlayer().getRecharge(), 0, "");
	}
	
	public void cleanInRank(long playerId) {
		for(RankerContext context : contextMap.values()) {
			Ranker ranker = context.deleteRank(playerId);
			if(ranker != null) {
				this.repository().delete(ranker);
			}
		}
	}
}
